package com.pig4cloud.pig.ads.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dy.sdk.client.DyTtClient;
import com.dy.sdk.model.request.tt.TtUpdateBidRequest;
import com.dy.sdk.model.request.tt.TtUpdateDayBudgetRequest;
import com.dy.sdk.model.request.tt.TtUpdateStatusRequest;
import com.dy.sdk.utils.DyConstant;
import com.google.common.collect.Lists;
import com.pig4cloud.pig.admin.api.entity.SysDictItem;
import com.pig4cloud.pig.ads.pig.mapper.AdCampaignMapper;
import com.pig4cloud.pig.ads.pig.mapper.AdPlanMapper;
import com.pig4cloud.pig.ads.pig.mapper.AdPromotionMapper;
import com.pig4cloud.pig.ads.pig.mapper.PlatformJobInfoMapper;
import com.pig4cloud.pig.ads.service.*;
import com.pig4cloud.pig.ads.utils.CronUtils;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.entity.*;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.core.util.DateUtil;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.api.dto.AdvertiserDto;
import com.pig4cloud.pig.api.dto.BudgetDto;
import com.pig4cloud.pig.api.dto.CampaignDto;
import com.pig4cloud.pig.api.enums.StatusEnum;
import com.pig4cloud.pig.api.util.CommonConstants;
import com.pig4cloud.pig.api.util.Constants;
import com.pig4cloud.pig.api.util.Page;
import com.pig4cloud.pig.api.vo.AdCampaignStatisticVo;
import com.pig4cloud.pig.api.vo.AdCreativeStatisticVo;
import com.pig4cloud.pig.api.vo.AdPlanStatisticVo;
import com.pig4cloud.pig.api.vo.AdStatisticCountVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author hma
 * @广告 报表查询 服务实现类
 */
@Log4j2
@Service
@RequiredArgsConstructor
public class AdvCampaignServiceImpl extends ServiceImpl<AdCampaignMapper, AdCampaign> implements AdvCampaignService {

	private final AdPromotionMapper adPromotionMapper;

	private final AdPlanMapper adPlanMapper;

	private final PlatformJobInfoMapper platformJobInfoMapper;

	@Autowired
	private TtAccesstokenService ttAccesstokenService;

	@Autowired
	private AdvService advService;

	private final StringRedisTemplate stringRedisTemplate;
	private final SysDictItemService sysDictItemService;
	private final TtCustomAudienceService ttCustomAudienceService;

	private final AdActionInterestService adActionInterestService;

	@Value("${ad_third_url}")
	private String adThirdUrl;
	@Value("${ad_update_plan_status_url}")
	private String updatePlanStatusUrl;

	@Value("${ad_update_campaign_status_url}")
	private String updateCampaignStatusUrl;


	@Value("${ad_update_creative_status_url}")
	private String updateCreativeStatusUrl;


	@Value("${ad_update_campaign_url}")
	private String updateCampaignUrl;

	@Value("${ad_update_ad_budget_url}")
	private String updateAdBudgetUrl;

	@Value("${ad_update_ad_bid_url}")
	private String updateAdBidUrl;

	@Value("${dict_cache_time}")
	private Long dictCacheTime;

	@Value("${adv_campaign_create_url}")
	private String  advCampaignCreateUrl;





	private static final String RETURN_STATUS_ALL_DELETE = "所有包含已删除";

	@Override
	public R findLatestOne(CampaignDto req) {
		if (null == req.getAdvertiserId()) {
			return R.failed("请选择广告账户id");
		}
		Integer userId = SecurityUtils.getUser().getId();
		AdCampaign adCampaign = baseMapper.selectOne(Wrappers.<AdCampaign>query().lambda().eq(AdCampaign::getAdvertiserId, req.getAdvertiserId())
				.eq(AdCampaign::getUserId, userId)
				.notIn(AdCampaign::getStatus, "CAMPAIGN_STATUS_DELETE")
				.orderByDesc(AdCampaign::getUpdateTime)
				.orderByDesc(AdCampaign::getCreateTime)
				.last("LIMIT 1"));

		return R.ok(adCampaign, "查询成功");
	}

	@Override
	public R findPage(CampaignDto req) {
		//设置分页条件
		Page page = new Page();
		page.setSize(req.getSize());
		page.setCurrent(req.getCurrent());
		//设置where条件
		QueryWrapper<AdCampaign> queryWrapper = new QueryWrapper<>();
		//状态不为删除状态
		queryWrapper.notIn("operation", "CAMPAIGN_STATUS_DELETE");
		//广告账户id
		if (null != req.getAdvertiserId()) {
			queryWrapper.eq("advertiser_id", req.getAdvertiserId());
		}
/*		//广告组id
		if (null != req.getCampaignId()){
			queryWrapper.like("campaign_id",req.getCampaignId());
		}*/
		//广告组名称
		if (null != req.getCampaignName()) {
			queryWrapper.like("campaign_name", req.getCampaignName());
		}
		//v2.4.2接入头条新营销链路后进查询 营销链路的广告组
		queryWrapper.ne("marketing_purpose","UNLIMITED");
		//根据修改时间降序
		queryWrapper.orderByDesc("campaign_modify_time");
		queryWrapper.orderByDesc("campaign_create_time");
		IPage<AdCampaign> data = baseMapper.selectPage(page, queryWrapper);
		return R.ok(data, "请求成功");
	}

	@Override
	public R createAdvCampaign(AdCampaign req) {
		String msg = this.baseCheck(req);
		if (StringUtils.isNotBlank(msg)) {
			return R.failed(msg);
		}
		//定义头条接口url
		String url = adThirdUrl+advCampaignCreateUrl;
		//获取广告投放账户
		//公共方法获取accessToken
        //设置广告组开启状态
		req.setStatus("enable");
		String accessToken = ttAccesstokenService.fetchAccesstoken(req.getAdvertiserId() + "");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", req.getAdvertiserId());
		data.put("campaign_name", req.getCampaignName());
		data.put("operation", req.getStatus());
		data.put("budget_mode", req.getBudgetMode());
		data.put("budget", req.getCampaignBudget());
		data.put("landing_type", req.getAdTarget());
		data.put("campaign_type",req.getCampaignType());
		data.put("marketing_purpose",req.getMarketingPurpose());

		String resultStr = OEHttpUtils.doPost(url, data, accessToken);
		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		//调用成功
		if (resBean != null && "0".equals(resBean.getCode())) {
			JSONObject jsonObj = resBean.getData();
			//设置广告组创建人
			Integer userId = SecurityUtils.getUser().getId();
			req.setUserId(userId.longValue());
			String campaign_id = jsonObj.getString("campaign_id");//获取第三方平台的 图片ID
			req.setCampaignId(Long.parseLong(campaign_id));
			//设置头条
			req.setAdType(1);
			//设置动游科技
			req.setBusinessType("001");
			req.setCreateTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
			req.setUpdateTime(DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
			//设置开启状态
			String status = req.getStatus();
			if ("enable".equals(status)) {
				status = "CAMPAIGN_STATUS_ENABLE";
				req.setStatus(status);
				req.setOptStatus(status);
			}
			if ("disable".equals(status)) {
				status = "CAMPAIGN_STATUS_DISABLE";
				req.setStatus(status);
				req.setOptStatus(status);
			}
			//插入本地数据库
			int insert = baseMapper.insert(req);
			if (insert > 0) {
				return R.ok(req, "广告组创建成功");
			}
		}
		return R.failed(resBean.getData(), resBean.getMessage());
	}

	private String baseCheck(AdCampaign req){
		//仅校验用户填写的
		if ("BUDGET_MODE_DAY".equals(req.getBudgetMode())) {
			if (req.getCampaignBudget() == null) {
				return "日预算不能为空";
			}
			if (req.getCampaignBudget().compareTo(BigDecimal.ZERO) <= 0
					|| req.getCampaignBudget().compareTo(new BigDecimal(300)) < 0) {
				return "日预算应不少于300元";
			}
		}
		if (StringUtils.isBlank(req.getCampaignName())) {
			return "广告组名称不能为空";
		}
		return "";
	}

	@Override
	public R getAdvCampaignStatistic(CampaignDto campaignDto) {
		//   1 查询对应的推广组表是否有数据，没有数据可以拉取一次， 通过缓存标志 当天是否已经拉取过一次，创建一次性任务，非每天循环拉取。如果已经拉取 就不再频繁拉取
		//  2 将拉取的数据存到统计表里面，并且查看推广组是否有对应的推广组信息，没有新增

		campaignDto.setType(StatusEnum.TYPE_ONE.getStatus());
		return getAdvStatistic(campaignDto);
	}

	/**
	 * 分页查询广告（推广组，广告计划，广告创意）报表数据
	 *
	 * @param campaignDto
	 * @return
	 */
	@Override
	public R getAdvStatistic(CampaignDto campaignDto) {
		try {
			List<Long> adverArr = null;
			if (null != campaignDto.getAdvertiserIds() && campaignDto.getAdvertiserIds().length > 0) {
				adverArr = Arrays.asList(campaignDto.getAdvertiserIds()).stream().map(Long::parseLong).collect(Collectors.toList());
			}

			if (0 == campaignDto.getSize()) {
				return R.failed("size  is  null ");
			}
			if (0 == campaignDto.getCurrent()) {
				return R.failed("current  is  null ");
			}
			if (null == campaignDto.getAdvertiserId()) {
				Integer id = null;
				try {
					id = SecurityUtils.getUser().getId();
				} catch (Exception e) {
					log.error("getAdvStatistic is error", e);
					return R.failed("query  is  exception:用户未登录 ");
				}
				if (CollectionUtils.isEmpty(adverArr)) {
					//获取当前账号下 广告账户列表
					List<String> allList = advService.getOwnerAdv(id, PlatformTypeEnum.TT.getValue());

					if (allList == null || allList.size() == 0) {
						return R.ok(new Page());
					}

					if (!CollectionUtils.isNotEmpty(allList)) {
						return R.ok(new Page());
					}
					adverArr = allList.stream().map(l -> Long.valueOf(l)).collect(Collectors.toList());

				}
				campaignDto.setAdvertiserArr(adverArr);
			} else {
				adverArr = new ArrayList<>();
				adverArr.add(campaignDto.getAdvertiserId());
				campaignDto.setAdvertiserArr(adverArr);
				campaignDto.setAdvertiserId(null);

			}
			//当没有传递时间的时候 默认统计当天的
			if (StringUtils.isBlank(campaignDto.getSdate())) {
				//数据能查询到的最早日期
				String sDate = "2016-10-26";
				campaignDto.setSdate(sDate);
			}
			if (StringUtils.isBlank(campaignDto.getEdate())) {
				campaignDto.setEdate(DateUtil.dateToString(new Date(), "yyyy-MM-dd"));
			}
			if (StringUtils.isNotBlank(campaignDto.getEdate())) {
				try {
					Date date = DateUtil.getDate(DateUtil.parse(campaignDto.getEdate().trim(), "yyyy-MM-dd"), 1);
					String edate = DateUtil.formatDate(date, "yyyy-MM-dd");
					campaignDto.setEdate(edate);
				} catch (Exception e) {
					log.error("getAdvCampaignStatistic  edate parseException", e);
					return R.failed("edate parseException ");
				}

			}
			//todo  统计单位时间内的平均点击率，花费
			AdCampaignStatistic adPlanStatisticCount=new AdCreativeStatisticVo();
			if (CollectionUtils.isNotEmpty(campaignDto.getAdvertiserArr())) {
				Page campaignStatisticVoList = null;

				if (StatusEnum.TYPE_ONE.getStatus().equals(campaignDto.getType())) {
					campaignStatisticVoList = baseMapper.selectAdCampaignStatisticList(new Page(campaignDto.getCurrent(), campaignDto.getSize()), campaignDto);
					if(CollectionUtils.isNotEmpty(campaignStatisticVoList.getRecords())){
                        //广告组合计 todo  设置缓存
						CampaignDto ct=campaignDto;
						ct.setOperate(CommonConstants.OPERATE_1);
						adPlanStatisticCount = baseMapper.selectAdCampaignStatisticList( ct);
					}


				} else if (StatusEnum.TYPE_TWO.getStatus().equals(campaignDto.getType())) {
					//广告计划分页查询
					campaignStatisticVoList = baseMapper.selectAdPlanStatisticList(new Page(campaignDto.getCurrent(), campaignDto.getSize()), campaignDto);
					if(CollectionUtils.isNotEmpty(campaignStatisticVoList.getRecords())){
						CampaignDto ct=campaignDto;
						ct.setOperate(CommonConstants.OPERATE_1);
						adPlanStatisticCount= baseMapper.selectAdPlanStatisticList( ct);
					}

				} else if (StatusEnum.TYPE_THREE.getStatus().equals(campaignDto.getType())) {
					//广告创意报表查询
					//todo  处理图片，视频类型
					//todo  处理状态
					campaignStatisticVoList = baseMapper.selectAdCreativeStatisticList(new Page(campaignDto.getCurrent(), campaignDto.getSize()), campaignDto);
					if(CollectionUtils.isNotEmpty(campaignStatisticVoList.getRecords())){
						CampaignDto ct=campaignDto;
						ct.setOperate(CommonConstants.OPERATE_1);
						adPlanStatisticCount = baseMapper.selectAdCreativeStatisticList( ct);
					}

				}
				// 根据拉取的数值 进行点击计算
				List<AdCampaignStatistic> list = campaignStatisticVoList.getRecords();

				List<AdCampaignStatistic> replaceList = new ArrayList<AdCampaignStatistic>();

				if (CollectionUtils.isNotEmpty(list)) {
					list.forEach(adCampaignStatistic -> {
						statisticCalculate(adCampaignStatistic);
						//处理操作状态
						adCampaignStatistic.setOptStatus(StringUtils.isNotBlank(adCampaignStatistic.getOptStatus()) ? getOptStatus(adCampaignStatistic.getOptStatus()) : "-");
						if (StatusEnum.TYPE_ONE.getStatus().equals(campaignDto.getType())) {
							//广告组数据转换
							AdCampaignStatisticVo adCampaignStatisticVo = new AdCampaignStatisticVo();
							BeanUtils.copyProperties(adCampaignStatistic, adCampaignStatisticVo);
							adCampaignStatisticVo.setAdTarget(transValue(adCampaignStatisticVo.getAdTarget()));
							adCampaignStatisticVo.setStatus(transValue(adCampaignStatisticVo.getStatus()));
//							if(StringUtils.isNotBlank(adCampaignStatisticVo.getBudgetMode())&&StringUtils.equals(adCampaignStatisticVo.getBudgetMode(),"BUDGET_MODE_INFINITE")){
//								adCampaignStatisticVo.setBudgetMode("--("+transValue(adCampaignStatisticVo.getBudgetMode())+")");
//							}else{
//								adCampaignStatisticVo.setBudgetMode(adCampaignStatisticVo.getCampaignBudget()+"("+transValue(adCampaignStatisticVo.getBudgetMode())+")");
//							}
							adCampaignStatisticVo.setCampaignBudget(adCampaignStatisticVo.getCampaignBudget());
							adCampaignStatisticVo.setAcTypeDesc(transValue(null != adCampaignStatisticVo.getAdType() ? adCampaignStatisticVo.getAdType().toString() : ""));
							adCampaignStatisticVo.setBusinessType(transValue(adCampaignStatisticVo.getBusinessType()));

							replaceList.add(adCampaignStatisticVo);
						} else if (StatusEnum.TYPE_TWO.getStatus().equals(campaignDto.getType())) {
							//广告计划数据转换
							AdPlanStatisticVo adPlanStatisticVo = new AdPlanStatisticVo();
							BeanUtils.copyProperties(adCampaignStatistic, adPlanStatisticVo);
							if (StringUtils.isNotBlank(adPlanStatisticVo.getInventoryType()) && StringUtils.equals(adPlanStatisticVo.getInventoryType(), "[]")) {
								String[] inventoryType = {"OTHER"};
								adPlanStatisticVo.setInventoryType(JSONObject.toJSONString(inventoryType));
							}
							adPlanStatisticVo.setInventoryType(inventory(adPlanStatisticVo.getInventoryType()));
							adPlanStatisticVo.setStatus(transValue(adPlanStatisticVo.getStatus()));
							adPlanStatisticVo.setAcTypeDesc(transValue(null != adPlanStatisticVo.getAdType() ? adPlanStatisticVo.getAdType().toString() : ""));
							adPlanStatisticVo.setUnionVideoType(transValue(adPlanStatisticVo.getUnionVideoType()));
							adPlanStatisticVo.setDeliveryRange(transValue(adPlanStatisticVo.getDeliveryRange()));
							adPlanStatisticVo.setDownloadType(transValue(adPlanStatisticVo.getDownloadType()));
							adPlanStatisticVo.setBudgetMode(adPlanStatisticVo.getBudget() + "(" + transValue(adPlanStatisticVo.getBudgetMode()) + ")");
							if (StringUtils.isNotBlank(adPlanStatisticVo.getPricing())) {
								String pricingSub = adPlanStatisticVo.getPricing().split("_")[adPlanStatisticVo.getPricing().split("_").length - 1];
								BigDecimal price = (null != adPlanStatisticVo.getBid() && adPlanStatisticVo.getBid().compareTo(new BigDecimal(0)) == 1) ? adPlanStatisticVo.getBid() : adPlanStatisticVo.getCpaBid();
								adPlanStatisticVo.setPricing(price + "(" + pricingSub + ")");
							}
							if (StringUtils.isNotBlank(adPlanStatisticVo.getScheduleType())) {
								//长期投放
								if (StringUtils.equals(adPlanStatisticVo.getScheduleType(), "SCHEDULE_FROM_NOW")) {
									adPlanStatisticVo.setScheduleType(transValue(adPlanStatisticVo.getScheduleType()));
								} else {
									adPlanStatisticVo.setScheduleType(adPlanStatisticVo.getStartTime() + "至" + adPlanStatisticVo.getEndTime());
								}
								Long scheduleDay=0L;
								String startTime=adPlanStatisticVo.getStartTime();
								if(StringUtils.isNotBlank(startTime)){
									//获取投放天数
									String endTime=adPlanStatisticVo.getEndTime();
									if(StringUtils.isEmpty(endTime) ){
										endTime=DateUtil.getTime();
									}else{
										if(DateUtil.stringToDate(endTime,"yyyy-MM-dd").getTime()> System.currentTimeMillis()){
											//当投放结束日期大于今天时间的时候，设置时间为今天
											endTime=DateUtil.getTime();
										}

									}
									//舍1法，整天计算在内，即排除当天投放天数
									scheduleDay=DateUtil.DayDate(DateUtil.stringToDate(endTime,"yyyy-MM-dd"),DateUtil.stringToDate(startTime,"yyyy-MM-dd"));

								}
								adPlanStatisticVo.setScheduleDay(scheduleDay);

							}
							adPlanStatisticVo.setConvertName(convertType(adPlanStatisticVo.getConvertName()));
							adPlanStatisticVo.setAdTarget(transValue(adPlanStatisticVo.getAdTarget()));
							//判断是否超出预警
							String costWarning = stringRedisTemplate.opsForValue().get(Constants.TT_REDIS_ADID_COST_WARNING_KEY_PRIX_ + adPlanStatisticVo.getAdId());
							adPlanStatisticVo.setCostWarning(StringUtils.isBlank(costWarning) ? "N" : costWarning);

							//添加性别，年龄，人群包，人群包排除，深度优化类型，学习期状态
							adPlanStatisticVo.setAge(transValueByDict(adPlanStatisticVo.getAge(),CommonConstants.OPERATE_1));
							adPlanStatisticVo.setGender(transValueByDict(adPlanStatisticVo.getGender(),CommonConstants.OPERATE_1));
							adPlanStatisticVo.setRetargetingTagsInclude(transValueByDict(adPlanStatisticVo.getRetargetingTagsInclude(),CommonConstants.OPERATE_2));
							adPlanStatisticVo.setRetargetingTagsExclude(transValueByDict(adPlanStatisticVo.getRetargetingTagsExclude(),CommonConstants.OPERATE_2));
							adPlanStatisticVo.setDeepBidType(transValueByDict(adPlanStatisticVo.getDeepBidType(),CommonConstants.OPERATE_1));
							adPlanStatisticVo.setLearningPhase(transValueByDict(adPlanStatisticVo.getLearningPhase(),CommonConstants.OPERATE_1));

							//定向包 兴趣
							adPlanStatisticVo.setActionScene(transValueByDict(adPlanStatisticVo.getActionScene(),CommonConstants.OPERATE_1));
							adPlanStatisticVo.setInterestActionMode(transValueByDict(adPlanStatisticVo.getInterestActionMode(),CommonConstants.OPERATE_1));
							//查询行为，兴趣类目，推荐关键词匹配
							adPlanStatisticVo.setActionCategories(transValueByDict(adPlanStatisticVo.getActionCategories(),CommonConstants.OPERATE_3));
							adPlanStatisticVo.setInterestCategories(transValueByDict(adPlanStatisticVo.getInterestCategories(),CommonConstants.OPERATE_4));
							adPlanStatisticVo.setActionWords(transValueByDict(adPlanStatisticVo.getActionWords(),CommonConstants.OPERATE_5));
							adPlanStatisticVo.setInterestWords(transValueByDict(adPlanStatisticVo.getInterestWords(),CommonConstants.OPERATE_6));
							replaceList.add(adPlanStatisticVo);

						} else if (StatusEnum.TYPE_THREE.getStatus().equals(campaignDto.getType())) {
							AdCreativeStatisticVo adCreativeStatisticVo = new AdCreativeStatisticVo();
							BeanUtils.copyProperties(adCampaignStatistic, adCreativeStatisticVo);
							adCreativeStatisticVo.setAcTypeDesc(transValue(null != adCreativeStatisticVo.getAdType() ? adCreativeStatisticVo.getAdType().toString() : ""));
							String createTypeDesc = "-";
							if (StatusEnum.TYPE_ONE.getStatus().equals(adCreativeStatisticVo.getCreativeType())) {
								createTypeDesc = "程序化创意";
							} else if (StatusEnum.TYPE_TWO.getStatus().equals(adCreativeStatisticVo.getCreativeType())) {
								createTypeDesc = "自定义创意";
							}
							adCreativeStatisticVo.setStatus(transValue(adCreativeStatisticVo.getStatus()));
							adCreativeStatisticVo.setCreativeTypeDes(createTypeDesc);
							adCreativeStatisticVo.setImageMode(transValue(adCreativeStatisticVo.getImageMode()));
							//类型  1 图片  2 视频
							String imageType = "-";
							if (StringUtils.isNotBlank(adCreativeStatisticVo.getImageMode())) {
								imageType = "1";
								if (adCreativeStatisticVo.getImageMode().contains("VIDEO")) {
									imageType = "2";
								}
							}
							adCreativeStatisticVo.setImgType(imageType);
							if (StringUtils.isNotBlank(adCreativeStatisticVo.getImageId())) {
								adCreativeStatisticVo.setImgUrl(baseMapper.getImageUrl(adCreativeStatisticVo.getImageId()));
							}
							if (StringUtils.isNotBlank(adCreativeStatisticVo.getVideoId())) {
								adCreativeStatisticVo.setVideoUrl(baseMapper.getVideoUrl(adCreativeStatisticVo.getVideoId()));
							}

							if (StringUtils.isNotBlank(adCreativeStatisticVo.getImageIds())) {
								//图片查询
								JSONArray jsonArray = JSON.parseArray(adCreativeStatisticVo.getImageIds());
								adCreativeStatisticVo.setImgUrl(baseMapper.getImageUrl(jsonArray.getString(0)));
							}


							replaceList.add(adCreativeStatisticVo);

						}

					});
				}
				campaignStatisticVoList.setRecords(replaceList);
				statisticCalculate(adPlanStatisticCount);
				AdStatisticCountVo adStatisticCountVo = new AdStatisticCountVo();
				BeanUtils.copyProperties(adPlanStatisticCount,adStatisticCountVo);
				campaignStatisticVoList.setRow(adStatisticCountVo);

				//todo  替换在前端页面创建定时任务拉取报表数据
				return R.ok(campaignStatisticVoList);
			} else {
				return R.failed("当前登录未绑定广告账号  !");
			}

		} catch (Exception e) {
			log.error("getAdvStatistic is error:", e);
			return R.failed("服务器异常请稍后重试 ");
		}

	}

	/**
	 * 统计计算对应的点击均价，千次展示进价，点击率，转化数，转化率
	 * @param ttStatistic
	 */
	public  void statisticCalculate(TtStatistic ttStatistic) {
		if (ttStatistic.getClick() > 0) {
			//点击均价
			ttStatistic.setAvgClickCost(ttStatistic.getCost().divide(new BigDecimal(ttStatistic.getClick()), 2, BigDecimal.ROUND_HALF_UP));

			//转化率  转化数/点击数*100%
			ttStatistic.setConvertRate(new BigDecimal(ttStatistic.getConvert()).multiply(new BigDecimal(100)).divide(new BigDecimal(ttStatistic.getClick()), 2, BigDecimal.ROUND_HALF_UP));

		}
		if (ttStatistic.getShow() > 0) {
			//千次展示均价
			ttStatistic.setAvgShowCost(ttStatistic.getCost().multiply(new BigDecimal(1000)).divide(new BigDecimal(ttStatistic.getShow()), 2, BigDecimal.ROUND_HALF_UP));
			//点击率=点击数/展示数
			ttStatistic.setCtr(new BigDecimal(ttStatistic.getClick()).multiply(new BigDecimal(100)).divide(new BigDecimal(ttStatistic.getShow()), 2, BigDecimal.ROUND_HALF_UP));
		}
		if(ttStatistic.getConvert() > 0){
			//转化成本 = 总花费/转化数
			ttStatistic.setConvertCost(ttStatistic.getCost().divide(new BigDecimal(ttStatistic.getConvert()), 2, BigDecimal.ROUND_HALF_UP));
		}



	}


	/**
	 * 修改广告推广告组状态
	 *
	 * @param advertiserDto
	 * @return
	 */
	@Override
	public R updateCampaignStatus(AdvertiserDto advertiserDto) {
		if (null == advertiserDto) {
			return R.failed("参数为空");
		}
		if (null == advertiserDto.getAdvertiserId()) {
			return R.failed("广告账号id不允许为空");
		}
		if (null == advertiserDto.getCampaignId()) {
			return R.failed("广告推广组id不允许为空");
		}
		if (null == advertiserDto.getOptStatus()) {
			return R.failed("操作状态不允许为空");
		}
		R r = updateThirdData(advertiserDto, StatusEnum.TYPE_ONE.getStatus());
		if (r.getCode() == 0) {
			String status = null;
			if (StringUtils.equals(advertiserDto.getOptStatus(), "enable")) {
				status = "CAMPAIGN_STATUS_ENABLE";
			} else if (StringUtils.equals(advertiserDto.getOptStatus(), "disable")) {
				status = "CAMPAIGN_STATUS_DISABLE";
			}
			baseMapper.updateAdCampaign(new AdCampaign(advertiserDto.getCampaignId(), status));
			return R.ok();
		} else {
			return r;
		}


	}


	/**
	 * 修改广告(广告组，广告创意)状态
	 *
	 * @param planDto
	 * @return
	 */
	public R updateThirdData(AdvertiserDto planDto, Integer type) {
		DyTtClient ttClient = new DyTtClient(DyConstant.TT_DEFAULT_ENDPOINT_EXPERIENCE);
		String token = ttAccesstokenService.fetchAccesstoken(planDto.getAdvertiserId().toString());       //convertTrackService.getAccesstoken(convertTrack);
		if (StringUtils.isBlank(token)) {
			return R.failed("当前账号token失效");
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("advertiser_id", planDto.getAdvertiserId());
		String url = null;
		if (StatusEnum.TYPE_ONE.getStatus().equals(type)) {
			//广告组状态修改
			Long[] campaignIds = {planDto.getCampaignId()};
			param.put("campaign_ids", campaignIds);
			param.put("opt_status", planDto.getOptStatus());
			url = updateCampaignStatusUrl;
		} else if (StatusEnum.TYPE_TWO.getStatus().equals(type)) {
			//广告计划状态修改
			Long[] adIds = {planDto.getAdId()};
			param.put("ad_ids", adIds);
			param.put("opt_status", planDto.getOptStatus());
			url = updatePlanStatusUrl;
		} else if (StatusEnum.TYPE_THREE.getStatus().equals(type)) {
			//广告创意状态修改
			Long[] creativeIds = {planDto.getCreativeId()};
			param.put("creative_ids", creativeIds);
			param.put("opt_status", planDto.getOptStatus());
			url = updateCreativeStatusUrl;
		} else if (StatusEnum.TYPE_FOUR.getStatus().equals(type)) {
			if(planDto.getVersionType().equals("2")){
				try {
					//新广告计划出价修改
					List<Map<String, Object>> paramList = new ArrayList<>();
					Map<String, Object> optStatusMap = new HashMap<String, Object>();
					optStatusMap.put("promotion_id", planDto.getAdId());
					optStatusMap.put("bid", planDto.getCpaBid());
					paramList.add(optStatusMap);
					TtUpdateBidRequest ttUpdateBidRequest=new TtUpdateBidRequest();
					ttUpdateBidRequest.setAdvertiser_id(planDto.getAdvertiserId());
					ttUpdateBidRequest.setData(paramList);
					String resultStr = ttClient.call4Post(ttUpdateBidRequest,token);
					//log.warn("updateThirdData response:" + resultStr);
					JSONObject obj = JSON.parseObject(resultStr);
					String code = obj.getString("code");
					if (!StringUtils.equals(code, "0")) {
						return R.failed("更新失败:" + obj.get("message"));
					}
					String data = obj.getString("data");
					return R.ok(data);
				} catch (IOException e) {
					e.printStackTrace();
					return R.failed("更新出价失败");
				}
			}
			//广告计划出价修改
			List<Map<String, Object>> paramList = new ArrayList<>();
			Map<String, Object> cpidMap = new HashMap<String, Object>();
			cpidMap.put("ad_id", planDto.getAdId());
			cpidMap.put("bid", planDto.getCpaBid());
			paramList.add(cpidMap);
			param.put("data", paramList);
			url = updateAdBidUrl;
		}
		String resultStr = OEHttpUtils.doPost(adThirdUrl + url, param, token);
		//log.warn("updateThirdData response:" + resultStr);
		JSONObject obj = JSON.parseObject(resultStr);
		String code = obj.getString("code");
		if (!StringUtils.equals(code, "0")) {
			return R.failed("更新失败:" + obj.get("message"));
		}
		String data = obj.getString("data");
		return R.ok(data);

	}


	/**
	 * 修改日预算（定时修改日预算【广告组、广告计划】）
	 *
	 * @param budgetDto
	 * @return
	 */
	@Override
	public R budgetUpdate(BudgetDto budgetDto, Integer operate) {
		try {
			String advertiserId = budgetDto.getAdvertiserId();
			Long unionId = null;
			String jobName = null;
			if (StatusEnum.OPERATE_TYPE_TWO.getStatus().intValue() == operate) {
				//推广组 ==1
				unionId = budgetDto.getCampaignId();
				QueryWrapper<AdCampaign> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("campaign_id", unionId);
				List<AdCampaign> advertising = baseMapper.selectList(queryWrapper);
				if (CollectionUtils.isEmpty(advertising)) {
					return R.failed("当前广告组不存在 !");
				}
				jobName = "修改头条广告推广组预算";
			} else if (StatusEnum.OPERATE_TYPE_THREE.getStatus().intValue() == operate) {
				//广告
				unionId = budgetDto.getAdId();
				if(budgetDto.getVersionType().equals("2")){
					QueryWrapper<AdPromotion> queryWrapper = new QueryWrapper<AdPromotion>();
					queryWrapper.eq("promotion_id", unionId);
					List<AdPromotion> adPromotions = adPromotionMapper.selectList(queryWrapper);
					if (CollectionUtils.isEmpty(adPromotions)) {
						return R.failed("当前广告计划不存在 !");
					}
					jobName = "修改头条体验版广告计划预算";
				}else {
					QueryWrapper<AdPlan> queryWrapper = new QueryWrapper<AdPlan>();
					queryWrapper.eq("ad_id", unionId);
					List<AdPlan> advertising = adPlanMapper.selectList(queryWrapper);
					if (CollectionUtils.isEmpty(advertising)) {
						return R.failed("当前广告计划不存在 !");
					}
					jobName = "修改头条广告计划预算";
				}
			}
			if (StringUtils.isNotBlank(budgetDto.getBudgetMode())) {
				if (budgetDto.getType().equals(StatusEnum.TYPE_ONE.getStatus())) {
					//修改今日日限额
					if (StringUtils.equals(budgetDto.getBudgetMode(), "BUDGET_MODE_DAY")) {
						//日限额
						if (null == budgetDto.getBudget()) {
							return R.failed("日预算不允许为空");
						}
					}
				}

			}
			BigDecimal budget = budgetDto.getBudget();
			if (null != budgetDto.getBudget()) {
				Boolean flag = budgetDto.getBudget().compareTo(new BigDecimal(300)) == -1 || budgetDto.getBudget().compareTo(new BigDecimal(9999999.99)) == 1;
				if (flag) {
					return R.failed("300  <=  budget   <= 9999999.99");
				}
			}
			String budgetMode = budgetDto.getBudgetMode();
			if (StatusEnum.TYPE_ONE.getStatus().equals(budgetDto.getType())) {
				//调用三方账号修改日预算
				if (StringUtils.isBlank(budgetMode)) {
					return R.failed("budgetMode is empty");
				}
				String token = ttAccesstokenService.fetchAccesstoken(budgetDto.getAdvertiserId());
				if (StringUtils.isBlank(token)) {
					return R.failed("advertising account does not exist !!");
				}
				//
				Map<String, Object> param = new HashMap<String, Object>();
				param.put("advertiser_id", advertiserId);
				param.put("budget_mode", budgetMode);
				if (StatusEnum.OPERATE_TYPE_TWO.getStatus().intValue() == operate) {
					param.put("campaign_id", budgetDto.getCampaignId());
					param.put("modify_time", DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
					param.put("budget", budget);
					String resultStr = OEHttpUtils.doPost(adThirdUrl + updateCampaignUrl, param, token);
					//log.warn("budgetUpdate response:" + resultStr);
					JSONObject obj = JSON.parseObject(resultStr);
					String code = obj.getString("code");
					if (!StringUtils.equals(code, "0")) {
						return R.failed("update budget exception" + obj.get("message"));
					}
					baseMapper.updateAdCampaign(new AdCampaign(budgetDto.getCampaignId(), budgetDto.getBudgetMode(), budgetDto.getBudget(), DateUtil.dateToString(new Date(), "yyyy-MM-dd HH:mm:ss")));
				} else if (StatusEnum.OPERATE_TYPE_THREE.getStatus().intValue() == operate) {

					if (budgetDto.getVersionType().equals("2")){
						DyTtClient ttClient = new DyTtClient(DyConstant.TT_DEFAULT_ENDPOINT_EXPERIENCE);
						//新广告计划状态修改
						List<Map<String, Object>> paramList = new ArrayList<>();
						Map<String, Object> optStatusMap = new HashMap<String, Object>();
						optStatusMap.put("promotion_id", budgetDto.getAdId());
						optStatusMap.put("budget", budgetDto.getBudget());
						paramList.add(optStatusMap);
						TtUpdateDayBudgetRequest ttUpdateStatusRequest=new TtUpdateDayBudgetRequest();
						ttUpdateStatusRequest.setAdvertiser_id(Long.valueOf(advertiserId));
						ttUpdateStatusRequest.setData(paramList);
						String resultStr = ttClient.call4Post(ttUpdateStatusRequest,token);
						log.info("new budgetUpdate response:" + resultStr);
						JSONObject obj = JSON.parseObject(resultStr);
						String code = obj.getString("code");
						if (!StringUtils.equals(code, "0")) {
							return R.failed("update budget exception" + obj.get("message"));
						}
						JSONObject returnData = obj.getJSONObject("data");
						JSONArray errorList = returnData.getJSONArray("errors");
						if (!errorList.isEmpty()) {
							String errorMsg = errorList.getJSONObject(0).getString("error_message");
							return R.failed("更新预算失败：" + errorMsg);
						}
						adPromotionMapper.updateByPrimaryKeySelective(new AdPromotion(budgetDto.getAdId(), budgetDto.getBudget(), null));
					}else {
						//支持批量修改预算
						List<Map<String, Object>> updateBudgetList = new ArrayList<>();
						Map<String, Object> updateMap = new HashMap<String, Object>();
						updateMap.put("ad_id", budgetDto.getAdId());
						updateMap.put("budget", budgetDto.getBudget());
						updateBudgetList.add(updateMap);
						param.put("data", updateBudgetList);
						String resultStr = OEHttpUtils.doPost(adThirdUrl + updateAdBudgetUrl, param, token);
						log.info("budgetUpdate response:" + resultStr);
						JSONObject obj = JSON.parseObject(resultStr);
						String code = obj.getString("code");
						if (!StringUtils.equals(code, "0")) {
							return R.failed("update budget exception" + obj.get("message"));
						}
						JSONObject returnData = obj.getJSONObject("data");
						JSONArray errorList = returnData.getJSONArray("errors");
						if (!errorList.isEmpty()) {
							String errorMsg = errorList.getJSONObject(0).getString("error_message");
							return R.failed("更新预算失败：" + errorMsg);
						}

						adPlanMapper.updateById(new AdPlan(budgetDto.getAdId(), budgetDto.getBudget(), null));
					}
				}

			} else {
				//创建定时任务，执行定时任务修改日预算
				if (null == budgetDto.getBudget()) {
					return R.failed("budget is empty");
				}
				//添加日限额方式
				budgetDto.setBudgetMode("BUDGET_MODE_DAY");
				//远程调用定时器项目创建定时任务
				try {
					//第二天凌晨执行
					Date exeTime = DateUtil.timeToBeginDay(DateUtil.getDate(new Date(), 1));
					String cronDate = CronUtils.getCron(exeTime);
					String exeParam = JSONObject.toJSONString(budgetDto);
					List<PlatformJobInfo> platformJobInfoList = platformJobInfoMapper.selectList(Wrappers.<PlatformJobInfo>query().lambda().eq(PlatformJobInfo::getUniqueId,unionId).eq(PlatformJobInfo::getOperateType,operate).eq(PlatformJobInfo::getType,StatusEnum.AD_TYPE_ONE.getStatus()).gt(PlatformJobInfo::getExecuteTime, new Date()));
					if (CollectionUtils.isEmpty(platformJobInfoList)) {
						//新增  -- 已经执行的以新增为标准，未执行以修改为准
						platformJobInfoMapper.insert(new PlatformJobInfo(unionId, jobName, cronDate, exeTime, exeParam, StatusEnum.JOB_STATUS_ONE.getStatus(), operate, StatusEnum.AD_TYPE_ONE.getStatus()));
					} else {
						//修改账号修改任务-----如果还没有执行
						platformJobInfoMapper.updateById(new PlatformJobInfo(unionId, exeParam, cronDate, exeTime, StatusEnum.JOB_STATUS_ONE.getStatus(), platformJobInfoList.get(0).getId()));
					}

				} catch (Exception e) {
					log.error("budgetUpdate  cron  is error:", e);
					return R.failed("定时修改日预算异常，请稍后重试");

				}

			}

			return R.ok();

		} catch (Exception e) {
			log.error("budgetUpdate is error", e);
			return R.failed("修改预算异常" + e.getMessage());
		}


	}


	/**
	 * 根据类型转换为对应的中文显示
	 *
	 * @param type
	 * @return
	 */
	public String transValue(String type) {
		if (StringUtils.isNotBlank(type)) {
			switch (type) {
				case "001":
					return "动游科技";
				case "INVENTORY_AWEME_FEED":
					return "抖音信息流";
				case "INVENTORY_VIDEO_FEED":
					return "西瓜信息流";
				case "INVENTORY_FEED":
					return "头条信息流";
				case "INVENTORY_TEXT_LINK":
					return "头条文章详情页";
				case "INVENTORY_HOTSOON_FEED":
					return "火山信息流";
				case "INVENTORY_UNION_SLOT":
					return "穿山甲";
				case "UNION_BOUTIQUE_GAME":
					return "穿山甲精选休闲游戏";
				case "INVENTORY_UNION_SPLASH_SLOT":
					return "穿山甲开屏广告";
				case "INVENTORY_AWEME_SEARCH":
					return "搜索广告——抖音位";
				case "INVENTORY_SEARCH":
					return "搜索广告——头条位";
				case "INVENTORY_UNIVERSAL":
					return "通投智选";
				case "INVENTORY_BEAUTY":
					return "轻颜相机";
				case "INVENTORY_PIPIXIA":
					return "皮皮虾";
				case "INVENTORY_AUTOMOBILE":
					return "懂车帝";
				case "INVENTORY_STUDY":
					return "好好学习";
				case "INVENTORY_FACE_U":
					return "faceu";
				case "OTHER":
					return "其他";

				case "LINK":
					return "销售线索收集";
				case "APP":
					return "应用推广";
				case "DPA":
					return "商品目录推广";
				case "GOODS":
					return "商品推广";
				case "STORE":
					return "门店推广";
				case "AWEME":
					return "抖音号推广";
				case "SHOP":
					return "电商店铺推广";
				case "ARTICAL":
					return "头条文章推广";

				case "BUDGET_MODE_DAY":
					return "日预算";
				case "BUDGET_MODE_TOTAL":
					return "总预算";
				case "BUDGET_MODE_INFINITE":
					return "不限";

//			   广告组状态
				case "CAMPAIGN_STATUS_ENABLE":
					return "启用";
				case "CAMPAIGN_STATUS_DISABLE":
					return "暂停";
				case "CAMPAIGN_STATUS_DELETE":
					return "删除";
				case "CAMPAIGN_STATUS_ALL":
					return RETURN_STATUS_ALL_DELETE;
				case "CAMPAIGN_STATUS_NOT_DELETE":
					return "所有不包含已删除（状态过滤默认值）";
				case "CAMPAIGN_STATUS_ADVERTISER_BUDGET_EXCEED":
					return "超出广告主日预算";

//			   广告计划状态
				case "AD_STATUS_ENABLE":
					return "启用";
				case "AD_STATUS_DISABLE":
					return "计划暂停";
				case "AD_STATUS_CAMPAIGN_DISABLE":
					return "已被广告组暂停";
				case "AD_STATUS_DELIVERY_OK":
					return "投放中";
				case "AD_STATUS_REAUDIT":
					return "修改审核中";
				case "AD_STATUS_AUDIT":
					return "新建审核中";
				case "AD_STATUS_DONE":
					return "已完成（投放达到结束时间）";
				case "AD_STATUS_CREATE":
					return "计划新建";
				case "AD_STATUS_AUDIT_DENY":
					return "审核不通过";
				case "AD_STATUS_BALANCE_EXCEED":
					return "账户余额不足）";
				case "AD_STATUS_BUDGET_EXCEED":
					return "超出预算";
				case "AD_STATUS_NOT_START":
					return "未到达投放时间";
				case "AD_STATUS_NO_SCHEDULE":
					return "不在投放时段";
				case "AD_STATUS_DELETE":
					return "已删除";
				case "AD_STATUS_CAMPAIGN_EXCEED":
					return "广告组超出预算";
				case "AD_STATUS_ALL":
					return RETURN_STATUS_ALL_DELETE;
				case "AD_STATUS_NOT_DELETE":
					return "所有不包含已删除";
				case "AD_STATUS_ADVERTISER_BUDGET_EXCEED":
					return "超出广告主日预算";

				case "1":
					return "头条";
				case "2":
					return "广点通";

				case "REWARDED_VIDEO":
					return "激励视频";
				case "ORIGINAL_VIDEO":
					return "原生";
				case "SPLASH_VIDEO":
					return "开屏";

				case "UNIVERSAL":
					return "通投智选";
				case "DEFAULT":
					return "默认";
				case "UNION":
					return "穿山甲";

				case "DOWNLOAD_URL":
					return "下载链接";
				case "QUICK_APP_URL":
					return "快应用+下载链接";
				case "EXTERNAL_URL":
					return "落地页链接";

				/*广告创意状态*/
				case "CREATIVE_STATUS_DELIVERY_OK":
					return "投放中";
				case "CREATIVE_STATUS_NOT_START":
					return "未到达投放时间";
				case "CREATIVE_STATUS_NO_SCHEDULE":
					return "不在投放时段";
				case "CREATIVE_STATUS_DISABLE":
					return "创意暂停";
				case "CREATIVE_STATUS_CAMPAIGN_DISABLE":
					return "已被广告组暂停";
				case "CREATIVE_STATUS_CAMPAIGN_EXCEED":
					return "广告组超出预算";
				case "CREATIVE_STATUS_AUDIT":
					return "新建审核中";
				case "CREATIVE_STATUS_REAUDIT":
					return "修改审核中";
				case "CREATIVE_STATUS_DELETE":
					return "已删除";
				case "CREATIVE_STATUS_DONE":
					return "已完成";
				case "CREATIVE_STATUS_AD_DISABLE":
					return "广告计划暂停";
				case "CREATIVE_STATUS_AUDIT_DENY":
					return "审核不通过";
				case "CREATIVE_STATUS_BALANCE_EXCEED":
					return "超出预算";
				case "CREATIVE_STATUS_PRE_ONLINE":
					return "预上线";
				case "CREATIVE_STATUS_AD_AUDIT":
					return "广告计划新建审核中";
				case "CREATIVE_STATUS_AD_REAUDIT":
					return "广告计划修改审核中";
				case "CREATIVE_STATUS_AD_AUDIT_DENY":
					return "广告计划审核不通过";
				case "CREATIVE_STATUS_ALL":
					return RETURN_STATUS_ALL_DELETE;
				case "CREATIVE_STATUS_NOT_DELETE":
					return "所有不包含已删除";
				case "CREATIVE_STATUS_ADVERTISER_BUDGET_EXCEED":
					return "超出账户日预算";

				/*创意素材类型*/
				case "CREATIVE_IMAGE_MODE_SMALL":
					return "小图，宽高比1.52，大小2M以下，下限：456 & 300，上限：1368 & 900";
				case "CREATIVE_IMAGE_MODE_LARGE":
					return "大图，横版大图宽高比1.78，大小2M以下，下限：1280 & 720，上限：2560 & 1440\t";
				case "CREATIVE_IMAGE_MODE_GROUP":
					return "组图，宽高比1.52，大小2M以下，下限：456 & 300，上限：1368 & 900";
				case "CREATIVE_IMAGE_MODE_VIDEO":
					return "横版视频，封面图宽高比1.78（下限：1280 & 720，上限：2560 & 1440））";
				case "CREATIVE_IMAGE_MODE_LARGE_VERTICAL":
					return "大图竖图，宽高比0.56，大小2M以下，下限：720 & 1280，上限：1440 & 2560";
				case "CREATIVE_IMAGE_MODE_VIDEO_VERTICAL":
					return "竖版视频，封面图宽高比0.56（9:16），下限：720 & 1280，上限：1440 & 2560";
				case "TOUTIAO_SEARCH_AD_IMAGE":
					return "广告计划修改审核中";
				case "SEARCH_AD_SMALL_IMAGE":
					return "搜索小图";
				case "CREATIVE_IMAGE_MODE_UNION_SPLASH":
					return "穿山甲开屏图片";
				case "CREATIVE_IMAGE_MODE_UNION_SPLASH_VIDEO":
					return "穿山甲开屏视频";
				case "CREATIVE_IMAGE_MODE_DISPLAY_WINDOW":
					return "搜索橱窗";
				case "MATERIAL_IMAGE_MODE_TITLE":
					return "标题类型，非创意的素材类型，仅报表接口会区分此素材类型";

				case "SCHEDULE_FROM_NOW":
					return "从今天起长期投放";
				case "SCHEDULE_START_END":
					return "设置开始和结束日期";
				default:
					return "-";
			}
		}
		return "-";

	}

	/**
	 * 当数据为数组的时候，返回对应的中文数据
	 *
	 * @param arrs
	 * @return
	 */
	public String inventory(String arrs) {
		if (StringUtils.isBlank(arrs)) {
			return null;
		}

		JSONArray jsonArray = JSON.parseArray(arrs);
		if (null != jsonArray && jsonArray.size() > 0) {
			StringBuffer stringBuffer = new StringBuffer("[");
			jsonArray.forEach(j -> {
				stringBuffer.append(transValue(j.toString()) + ",");
			});
			stringBuffer.delete(stringBuffer.lastIndexOf(","), stringBuffer.length());
			stringBuffer.append("]");
			return stringBuffer.toString();
		}

		return null;
	}

	/**
	 * 转换目标
	 *
	 * @param convertType
	 * @return
	 */
	private String convertType(String convertType) {
		if (StringUtils.isBlank(convertType)) {
			return "-";
		}
		switch (convertType) {
			case "4":
				return "下载完成";
			case "8":
				return "激活";
			case "13":
				return "激活且注册";
			case "14":
				return "激活且付费";
			case "15":
				return "安装完成";
			case "25":
				return "关键行为";
			case "30":
				return "账号关注";
			default:
				return "-";

		}
	}


	/**
	 * 查询操作状态
	 *
	 * @param optStatus
	 * @return
	 */
	private String getOptStatus(String optStatus) {
		if (StringUtils.isBlank(optStatus)) {
			return "-";
		}
		switch (optStatus) {
			case "CAMPAIGN_STATUS_ENABLE":
			case "CREATIVE_STATUS_ENABLE":
			case "AD_STATUS_ENABLE":
				return "enable";
			case "CAMPAIGN_STATUS_DISABLE":
			case "CREATIVE_STATUS_DISABLE":
			case "AD_STATUS_DISABLE":
				return "disable";
			case "CAMPAIGN_STATUS_DELETE":
			case "CREATIVE_STATUS_DELETE":
				return "delete";
			default:
				return "-";
		}
	}


	/**
	 * 根据字段数据转换数据
	 * @return
	 */
	public String transValueByDict(String  value,Integer operate){
		if(StringUtils.isNotBlank(value)){
			Boolean arrFlag=Boolean.FALSE;
			Integer actionInterestType=null;
			if(value.startsWith("[")&&value.endsWith("]")){
				value=value.replace("[","").replace("]","");
				arrFlag=Boolean.TRUE;
			}
			String[] valArr= {};
			if(StringUtils.isNotEmpty(value)){
				valArr=value.split(",");
			}
			StringBuffer returnVal=new StringBuffer();
			if(arrFlag){
				returnVal.append("[");
			}
			List<SysDictItem> itemList= Lists.newArrayList();
			String dictKeyValue = stringRedisTemplate.opsForValue().get(Constants.DICT_KEY_PRIX_+operate );
			if(StringUtils.isNotBlank(dictKeyValue)){
				itemList= JSONObject.parseArray(dictKeyValue,SysDictItem.class);
			}else{
				if(CommonConstants.OPERATE_1 ==operate){
					//根据字段值进行匹配
					itemList = sysDictItemService.list(Wrappers.<SysDictItem>query().lambda().eq(SysDictItem::getDelFlag,CommonConstants.STATUS_NORMAL));
				}else if(CommonConstants.OPERATE_2 ==operate){
					//根据人群包字典表进行匹配
					List<TtCustomAudience>  ttCustomAudienceList= ttCustomAudienceService.list(Wrappers.<TtCustomAudience>query().lambda().eq(TtCustomAudience::getIsdel,CommonConstants.STATUS_NORMAL));
					SysDictItem sysDictItem=null;
					for(TtCustomAudience ttCustomAudience:ttCustomAudienceList){
						sysDictItem=new SysDictItem();
						sysDictItem.setLabel(ttCustomAudience.getName());
						sysDictItem.setValue(ttCustomAudience.getCustomAudienceId().toString());
						itemList.add(sysDictItem);
					}


				}else if(CommonConstants.OPERATE_3 ==operate||CommonConstants.OPERATE_4 ==operate||CommonConstants.OPERATE_5 ==operate||CommonConstants.OPERATE_6 ==operate){
					//查询行为类目  //查询兴趣类目     //查询行为推荐词  //查询兴趣推荐词
					if(CommonConstants.OPERATE_3 ==operate){
						actionInterestType=CommonConstants.TYPE_1;
					}else if(CommonConstants.OPERATE_4 ==operate){
						//查询兴趣类目
						actionInterestType=CommonConstants.TYPE_2;
					}else if(CommonConstants.OPERATE_5 ==operate){
						//查询行为推荐词
						actionInterestType=CommonConstants.TYPE_3;
					}else if(CommonConstants.OPERATE_6 ==operate){
						//查询兴趣推荐词
						actionInterestType=CommonConstants.TYPE_4;

					}
					List<AdActionInterest> adActionInterestList=adActionInterestService.list(Wrappers.<AdActionInterest>query().lambda().eq(AdActionInterest::getType,actionInterestType));
					SysDictItem sysDictItem=null;
					for(AdActionInterest adActionInterest:adActionInterestList){
						sysDictItem=new SysDictItem();
						sysDictItem.setLabel(adActionInterest.getName());
						sysDictItem.setValue(adActionInterest.getThirdId().toString());
						itemList.add(sysDictItem);
					}

				}

				String itemStr= JSONObject.toJSONString(itemList);
				//设置5分钟缓存
				stringRedisTemplate.opsForValue().set(Constants.DICT_KEY_PRIX_+operate,itemStr,dictCacheTime, TimeUnit.MINUTES);
			}
			if(CollectionUtils.isNotEmpty(itemList)){

				Integer length=0;
				for(String str:valArr){
					String replaceStr=str.replace("\"","").replace("\"","");
					length++;
					List<SysDictItem> filterItem=itemList.stream().filter(sysDictItem -> replaceStr.equals(sysDictItem.getValue())).collect(Collectors.toList());
					if(CollectionUtils.isNotEmpty(filterItem)){
						returnVal.append(filterItem.get(0).getLabel());

					}else{
						returnVal.append(str);
					}
					if(length < valArr.length){
						returnVal.append(",");
					}

				}

				if(arrFlag){
					returnVal.append("]");
				}
			}


			return  returnVal.toString();
		}
		return "--";

	}


}
